package com.pay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pay.dto.BusinessDto;
import com.pay.dto.ResponseEntity;
import com.pay.dto.VerifyDto;
import com.pay.entity.TbBusiness;
import com.pay.entity.TbBusinessDetails;
import com.pay.entity.TbBusinessOrder;
import com.pay.mapper.TbBusinessDetailsMapper;
import com.pay.mapper.TbBusinessOrderMapper;
import com.pay.service.TbBusinessService;
import com.pay.mapper.TbBusinessMapper;
import com.pay.utils.ALiBaBaBankCard;
import com.pay.utils.AliBaBaIdentity;
import com.pay.utils.MessageUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Transactional
@Service
public class TbBusinessServiceImpl extends ServiceImpl<TbBusinessMapper, TbBusiness>
    implements TbBusinessService{
    @Resource
    TbBusinessMapper tbBusinessMapper;
    @Resource
    TbBusinessDetailsMapper tbBusinessDetailsMapper;
    @Resource
    TbBusinessOrderMapper tbBusinessOrderMapper;

    Logger logger= LogManager.getLogger();

    @Override
    public ResponseEntity checkNameAndPhone(VerifyDto verifyDto) {
        //查询用户名
        QueryWrapper<TbBusiness> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(TbBusiness::getBusinessName,verifyDto.getBusinessName());
        List<TbBusiness> tbBusinessNameList = tbBusinessMapper.selectList(wrapper);
        //判断用户名是否存在
        if(tbBusinessNameList.size()>0){
            return new ResponseEntity(null,500,"该用户名已经存在",false);
        }
        //查询手机号
        QueryWrapper<TbBusiness> wrapper1 = new QueryWrapper<>();
        wrapper.lambda().eq(TbBusiness::getBusinessPhone,verifyDto.getBusinessPhone());
       List<TbBusiness> tbBusinessPhoneList = tbBusinessMapper.selectList(wrapper1);
       //判断手机号是否存在
        if(tbBusinessPhoneList.size()>0){
            return new ResponseEntity(null,500,"该手机号已经存在",false);
        }
        return new ResponseEntity(null,200,"可以使用",true);
    }

    @Override
    public ResponseEntity checkIdentity(VerifyDto verifyDto) {
        //调用阿里云接口对身份信息进行验证
        AliBaBaIdentity aliBaBaIdentity = new AliBaBaIdentity();
        Map<String,Object> reslutMap=new HashMap<>();
        try {
            reslutMap = aliBaBaIdentity.Identity(verifyDto.getBusinessRname(), verifyDto.getBusinessNumber());
        }catch (Exception e){
            e.printStackTrace();
            logger.error("身份证验证异常："+e.getMessage());
        }
        Integer code = (Integer) reslutMap.get("code");
        if(code!=200){
            return new ResponseEntity(null,500,"验证失败",false);
        }
        return new ResponseEntity(reslutMap,200,"验证无问题",true);
    }

    @Override
    public ResponseEntity checkAccount(VerifyDto verifyDto) {
        ALiBaBaBankCard aLiBaBaIdCard = new ALiBaBaBankCard();
        String checkCard=null;
        try {
            checkCard = aLiBaBaIdCard.checkCard(verifyDto.getBusinessRname(), verifyDto.getBusinessAccount(),
                    verifyDto.getBusinessNumber(), verifyDto.getBusinessPhone());
        }catch (Exception e){
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.parseObject(checkCard);
        JSONObject resp = jsonObject.getJSONObject("resp");
        Integer code = resp.getInteger("code");
        if(code!=200){
            return new ResponseEntity(null,500,"该银行卡不可用",false);
        }
        return new ResponseEntity(null,200,"该银行卡可以使用",true);
    }

    @Override
    public ResponseEntity checkLicense(VerifyDto verifyDto) {
        //根据searchKey进行查询
        QueryWrapper<TbBusinessDetails> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(TbBusinessDetails::getBusinessLicense,verifyDto.getBusinessLicense());
        List<TbBusinessDetails> detailsList = tbBusinessDetailsMapper.selectList(wrapper);
        if(detailsList.size()<=0){
            return new ResponseEntity(null,500,"该营业执照已注销",false);
        }
        return new ResponseEntity(detailsList,200,"该营业执照可以正常使用",true);
    }

    @Override
    public ResponseEntity saveBusiness(BusinessDto businessDto) {
        TbBusiness tbBusiness = new TbBusiness();
        TbBusinessDetails businessDetails = new TbBusinessDetails();
        String pwd=null;
        try {
            //添加商家注册表
            tbBusiness.setBusinessName(businessDto.getBusinessName());
            tbBusiness.setBusinessPhone(businessDto.getBusinessPhone());
            //使用BCrypt加密密码后添加到数据库
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            pwd = encoder.encode(businessDto.getBusinessPwd());
            tbBusiness.setBusinessPwd(pwd);
            //添加商家注册表
            tbBusinessMapper.insert(tbBusiness);
            //根据商家注册表的id添加商家详情表
            businessDetails.setBusinessId(tbBusiness.getBusinessId());
            businessDetails.setBusinessAccount(businessDto.getBusinessAccount());
            businessDetails.setBusinessAccountName(businessDto.getBusinessAccountName());
            businessDetails.setBusinessLicense(businessDto.getBusinessLicense());
            businessDetails.setBusinessNumber(businessDto.getBusinessNumber());
            businessDetails.setBusinessRname(businessDto.getBusinessRname());
            //注册时间
            businessDetails.setBusinessTime(LocalDateTime.now());
            //财务人员审核状态
            businessDetails.setBusinessMoneyStatus(0);
            //管理员审核状态
            businessDetails.setBusinessState(0);
            tbBusinessDetailsMapper.insert(businessDetails);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("商家注册异常："+e.getMessage());
            return new ResponseEntity(null,500,"商家注册失败",false);
        }
        return new ResponseEntity(null,200,"商家注册成功",true);
    }

    @Override
    public ResponseEntity updateState(BusinessDto businessDto, String token) {
        Claims claims = Jwts.parser().setSigningKey("huangyujie").parseClaimsJws(token).getBody();
        int uid = Integer.parseInt(claims.getId());
        MessageUtils messageUtils = new MessageUtils();
        //根据解析的token查询商家注册表
        TbBusiness tbBusiness = tbBusinessMapper.selectById(uid);
        //调用权限的接口查询是否是管理员
        //修改状态
        TbBusinessDetails details = new TbBusinessDetails();
        details.setDetailsId(businessDto.getDetailsId());
        details.setBusinessState(1);
        //修改
        int updateById = tbBusinessDetailsMapper.updateById(details);
        String code=null;
        //审核通没通过都发送短信
        try {
            code = messageUtils.sendMessage(tbBusiness.getBusinessPhone(),updateById);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("发送短信异常："+e.getMessage());
        }
        if(Integer.parseInt(code)!=200){
            return new ResponseEntity(null,500,"短信发送失败",false);
        }
        return new ResponseEntity(null,200,"修改成功",true);
    }

    @Override
    public ResponseEntity updateMoneyState(BusinessDto businessDto, String token) {
        Claims claims = Jwts.parser().setSigningKey("huangyujie").parseClaimsJws(token).getBody();
        int uid = Integer.parseInt(claims.getId());
        //调用权限来判断角色是否是财务人员
        //是财务人员的话，则根据支付状态来判断是否已经缴费
        TbBusinessOrder tbBusinessOrder = tbBusinessOrderMapper.selectOrder(uid,businessDto.getOrderNum());
        if(tbBusinessOrder.getPayState()<=0){
            return new ResponseEntity(null,500,"还未支付",false);
        }
        //支付完成后，修改状态
        TbBusinessDetails details = new TbBusinessDetails();
        details.setDetailsId(businessDto.getDetailsId());
        details.setBusinessMoneyStatus(1);
        tbBusinessDetailsMapper.updateById(details);
        return new ResponseEntity(null,200,"修改成功",true);
    }

    @Override
    public ResponseEntity searchBusinessList() {
        QueryWrapper<TbBusinessDetails> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(TbBusinessDetails::getBusinessState,0);
        List<TbBusinessDetails> detailsList = tbBusinessDetailsMapper.selectList(wrapper);
        return new ResponseEntity(detailsList,200,"查询成功",true);
    }
}




